<?php

require_once dirname(dirname(__FILE__)) . '/config/ConfigLoader.php';
require_once dirname(dirname(__FILE__)) . '/vendor/autoload.php';
require_once dirname(dirname(__FILE__)) . '/database/DBManager.php';
require_once dirname(dirname(dirname(__FILE__))) . "/database/tables/table_application_nodeArray.php";
require_once dirname(dirname(dirname(__FILE__))) . "/database/tables/table_application_sensorData.php";
require_once dirname(dirname(dirname(__FILE__))) . "/database/tables/table_application_nodelocalinfo.php";

use \PhpMqtt\Client\MqttClient;
use \PhpMqtt\Client\ConnectionSettings;
use PhpMqtt\Client\Exceptions\MqttClientException;

global $mqtt;

TableArray("table_application_nodeArray")->deleteAll();
mqttConnect();
mqttInit();

$mqtt->loop(true);

mqttDisconnect();


function mqttConnect()
{
    $server   = '183.230.40.39';
    $port     = 6002;
    $clientId = 1124904681; //1105034121
    $username = '601964'; //611914
    $password = 'hMkHTSwsfmHK6sApzV0l3qEjsTE=';
    $clean_session = true;
    global $mqtt;

    $connectionSettings  = (new ConnectionSettings)
        ->setUsername($username)
        ->setPassword($password)
        ->setKeepAliveInterval(120)
        // Last Will 设置
        ->setLastWillTopic(null)
        ->setLastWillMessage(null)
        ->setLastWillQualityOfService(1);

    $mqtt = new MqttClient($server, $port, $clientId, MqttClient::MQTT_3_1_1, null);
    $mqtt->connect($connectionSettings, $clean_session);
    if ($mqtt->isConnected()) {
        console("client connected");
    } else {
        console("client disconnected");
    }
}

function mqttInit()
{
    global $mqtt;
    $mqtt->subscribe(MQTT_TopicGatewaySync, function ($topic, $message) {
        global $mqtt;

        $splitMessage = array();
        $splitMessage = explode('_', $message);
        $mqtt->subscribe($splitMessage[0] . MQTT_TopicNodeSync, function ($topic, $message) {
            global $mqtt;
            console($topic . $message);
            $splitMessage = array();
            $splitMessage = explode('~', $message);
            /**
             * 将传感器节点的信息上传到数据库
             * 
             */
            $where = "";
            $where .= COLUMN_Gateway . "='" . $splitMessage[0] . "'";
            $where .= " AND ";
            $where .= COLUMN_NodeName . "='" . $splitMessage[1] . "'";
            $alldata = TableArray("table_application_nodeArray")->fetch_all_assoc($where);
            $data = array();
            $data[COLUMN_Gateway] = $splitMessage[0];
            $data[COLUMN_NodeName] = $splitMessage[1];
            $data[COLUMN_NodeState] = 1;
            $data[COLUMN_SensorNum] = $splitMessage[2];
            $data[COLUMN_SensorTypeArray] = $splitMessage[3];

            if (count($alldata) == 0) {
                TableArray("table_application_nodeArray")->insert($data);
            } else {
                TableArray("table_application_nodeArray")->update($data, $where);
            }

            $mqtt->subscribe($splitMessage[0] . '/' . $splitMessage[1] . '/#', function ($topic, $message) {
                global $TableSensorDataHeaderArray;
                $splitMessage = explode('_', $message);
                //console($topic . $message);
                $data = array();
                $data[COLUMN_Gateway] = $splitMessage[0];
                $data[COLUMN_NodeName] = $splitMessage[1];
                $data[COLUMN_Time] = date('Y-m-d H:i:s');
                $data[COLUMN_BatteryLevel] = $splitMessage[2];
                $data[COLUMN_SensorNum] = $splitMessage[3];
                for ($i = 0; $i < $splitMessage[3]; $i++) {
                    $data[$TableSensorDataHeaderArray[6 + $i * 2]] = $splitMessage[4 + $i * 2];
                    $data[$TableSensorDataHeaderArray[7 + $i * 2]] = $splitMessage[5 + $i * 2];
                }
                TableArray("table_application_sensorData")->insert($data);
            }, 1);
        }, 1);

        $mqtt->subscribe($splitMessage[0] . MQTT_TopicNodeLocalSyncRequest, function ($topic, $message) {
            global $mqtt;
            $splitMessage = array();
            $splitMessage = explode('_', $message);
            $where = "";
            $where .= COLUMN_Gateway . "='" . $splitMessage[0] . "'";
            $alldata = TableArray("table_application_nodelocalinfo")->fetch_all_assoc($where);

            for ($i = 1; $i <= count($alldata); $i++) {
                if ($alldata[$i][COLUMN_Gateway] == $splitMessage[0]) {
                    $payload = $alldata[$i][COLUMN_Gateway];
                    $payload .= "~";
                    $payload .= $alldata[$i][COLUMN_NodeName];
                    $payload .= "~";
                    $payload .= $alldata[$i][COLUMN_Area];
                    $payload .= "~";
                    $payload .= $alldata[$i][COLUMN_LocalInfo];
                    console($payload);
                    $mqtt->publish(
                        // topic
                        $splitMessage[0] . MQTT_TopicNodeLocalSync,
                        // payload
                        $payload,
                        // qos
                        0,
                        // retain
                        false
                    );
                }
            }
        }, 1);

        $mqtt->publish(
            // topic
            $splitMessage[0] . MQTT_TopicNodeSyncRequest,
            // payload
            "1",
            // qos
            0,
            // retain
            false
        );
    }, 0);

    $mqtt->subscribe(MQTT_TopicGatewayWill, function ($topic, $message) {
    }, 0);

    $mqtt->publish(
        // topic
        MQTT_TopicGatewaySyncRequest,
        // payload
        "1",
        // qos
        0,
        // retain
        false
    );
}

function mqttDisconnect()
{
    global $mqtt;
    $mqtt->disconnect();
    if ($mqtt->isConnected()) {
        console("lient connected");
    } else {
        console("client disconnected");
    }
}

function messageCallBack($topic, $message)
{
}
